#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <pthread.h>

// 全局变量，用于记录接收到的信号数量
volatile sig_atomic_t sigint_count = 0;
volatile sig_atomic_t sig40_count = 0;

// SIGINT 信号处理函数
void handle_sigint(int sig) {
    sigint_count++;
    printf("Caught SIGINT (%d times)\n", sigint_count);
}

// 40号信号处理函数
void handle_sig40(int sig) {
    sig40_count++;
    printf("Caught signal 40 (%d times)\n", sig40_count);
}

// 线程函数，用于发送信号
void* send_signals(void* arg) {
    int sig = *(int*)arg;
    for (int i = 0; i < 5; i++) {
        kill(getpid(), sig);
        sleep(1); // 每次发送信号后暂停1秒
    }
    return NULL;
}

int main() {
    struct sigaction sa;
    sigset_t mask;

    // 初始化信号集，并添加 SIGINT 和 SIGRTMIN+8 到信号集中
    sigemptyset(&mask);
    sigaddset(&mask, SIGINT);
    sigaddset(&mask, SIGRTMIN+8);
    sigprocmask(SIG_BLOCK, &mask, NULL);

    // 设置 SIGINT 的信号处理函数
    sa.sa_handler = handle_sigint;
    sa.sa_flags = 0;
    sigemptyset(&sa.sa_mask);
    if (sigaction(SIGINT, &sa, NULL) == -1) {
        perror("sigaction");
        exit(1);
    }

    // 设置 40号信号（SIGRTMIN+8）的信号处理函数
    sa.sa_handler = handle_sig40;
    if (sigaction(SIGRTMIN+8, &sa, NULL) == -1) {
        perror("sigaction");
        exit(1);
    }

    // 创建线程发送 SIGINT 信号
    pthread_t thread_sigint;
    int sigint = SIGINT;
    if (pthread_create(&thread_sigint, NULL, send_signals, &sigint) != 0) {
        perror("pthread_create");
        exit(1);
    }

    // 创建线程发送 40号信号
    pthread_t thread_sig40;
    int sig40 = SIGRTMIN+8;
    if (pthread_create(&thread_sig40, NULL, send_signals, &sig40) != 0) {
        perror("pthread_create");
        exit(1);
    }

    // 等待线程结束
    pthread_join(thread_sigint, NULL);
    pthread_join(thread_sig40, NULL);

    // 解除信号阻塞
    sigprocmask(SIG_UNBLOCK, &mask, NULL);

    printf("SIGINT was caught %d times.\n", sigint_count);
    printf("Signal 40 was caught %d times.\n", sig40_count);

    return 0;
}
